﻿using AppSocketModel;
using AppSocketService.Account;
using AppSocketService.Company;
using BCGPSCommon;
using BCGPSMongoData;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace AppSocketService.Product
{
    public class ProductService : ServiceBase, IProductService
    {
        private MongoDBCommand<ProductDto> mongoDBCommand = new MongoDBCommand<ProductDto>("Procuct");
        private readonly AccountDto CurrentAccount;
        private readonly IRedisService redisService;
        private readonly ICompanyService companyService;

        public ProductService(IClaimsAccessor claimsAccesso, IRedisService redisService, IAccountService accountService, IAccountPersonService accountPersonService, ISystemAccountService systemAccountService, ICompanyService companyService) : base(claimsAccesso)
        {
            this.redisService = redisService;
            this.companyService = companyService;

            if (claimsAccesso.AccountRole == AccountRole.SYSTEM)
                CurrentAccount = systemAccountService.GetCurrentAccount().AsAccountDto();
            else if (claimsAccesso.AccountRole == AccountRole.Company)
                CurrentAccount = accountService.GetCurrentAccount();
            else if (claimsAccesso.AccountRole == AccountRole.PERSON)
                CurrentAccount = accountPersonService.GetCurrentAccount();
        }

        public ProductService()
        {
        }

        public ProductDto Get(string imei)
        {
            return mongoDBCommand.SelectDocumentAsync(s => s.IMEI == imei).GetAwaiter().GetResult();
        }

        public bool IsExist(string imei)
        {
            if (Get(imei) != null)
                return true;
            else
                return false;
        }

        #region 批量添加 
        public int Add(ProductRequestDto productRequestDto)
        {
            if (productRequestDto.imeiList == null || productRequestDto.imeiList.Count <= 0)
                throw new ArgumentException("没有检测到正确的IMEI !");

            ProductDto dto = productRequestDto.As<ProductDto>();
            int count = 0;
            foreach (var item in productRequestDto.imeiList)
            {
                if (IsExist(item))
                    throw new ArgumentException($"错误: IMEI[{item}]已存在! 本次添加成功[{count}]个产品!");
                dto.Id = string.Empty;
                dto.IMEI = item;
                dto.deviceCategory = DeviceCategory.GPS;
                dto.lifeStatus = LifeStatus.NEW;
                dto.CreateDateTime = BCGPSCommon.MongoDBDateTime.GetNowUtc();
                dto.CreateAccountCode = CurrentAccount.AccountCode;
                dto.CreateAccountRole = CurrentAccount.AccountRole;
                mongoDBCommand.InsertDocumentAsync(dto).GetAwaiter().GetResult();
                count++;
            }
            return count;

        }
        #endregion

        #region 删除 
        public long DeleteList(List<string> imeiList)
        {
            long count = 0;
            foreach (var item in imeiList)
            {
                count += Delete(item);
            }
            return count;
        }

        public long Delete(string imei)
        {
            return mongoDBCommand.DeleteDocumentAsync(s => s.IMEI == imei).GetAwaiter().GetResult().DeletedCount;
        }
        #endregion

        #region  修改基础信息
        public ProductDto UpdateBaseInfo(ProductDto dto)
        {
            dto.ModifyDateTime = BCGPSCommon.MongoDBDateTime.GetNowUtc();
            dto.ModifyAccountCode = CurrentAccount.AccountCode;
            dto.ModifyAccountRole = CurrentAccount.AccountRole;

            var update = Builders<ProductDto>.Update
                    .Set(s => s.deviceCategory, dto.deviceCategory)
                    .Set(s => s.deviceType, dto.deviceType)
                    .Set(s => s.lifeStatus, dto.lifeStatus)
                    .Set(s=>s.Model,dto.Model)
                    .Set(s=>s.ModifyAccountRole ,dto.ModifyAccountRole)
                    .Set(s => s.ModifyDateTime, dto.ModifyDateTime)
                    .Set(s => s.ModifyAccountCode, dto.ModifyAccountCode);
            var ret = mongoDBCommand.UpdateDocumentAsync(s => s.IMEI == dto.IMEI, update).GetAwaiter().GetResult();
            if (ret == null)
                throw new ArgumentException("修改失败,请重试!");

            return ret;
        }
        #endregion

        #region 批量修改购买信息
        public int UpdateBuyInfo(ProductBuyInfoDto dto)
        {
            var company = companyService.Get(dto.CompanyId);
            if (company == null)
                throw new ArgumentException("公司信息不存在,请先录入公司信息!");

            int count = 0;
            foreach (var item in dto.ImeiList)
            {
                var update = Builders<ProductDto>.Update
                        .Set(s => s.ModifyDateTime, BCGPSCommon.MongoDBDateTime.GetNowUtc())
                        .Set(s => s.ModifyAccountCode, CurrentAccount.AccountCode)
                        .Set(s => s.CompanyId, dto.CompanyId)
                        .Set(s => s.CompanyName, company.CompanyName)
                        .Set(s => s.BuyDate, dto.BuyDate);

                var ret = mongoDBCommand.UpdateDocumentAsync(s => s.IMEI == item, update).GetAwaiter().GetResult();
                if (ret == null)
                    throw new ArgumentException("修改失败,请重试!");
                count++;
            }
            return count;
        }
        #endregion

        #region  获取列表
        public PageableList<ProductDto> GetList(DeviceType? deviceType, LifeStatus? lifeStatus,string model,string accountCode,  string imei, DateTime? start, DateTime? end,  bool desc, int index, int size)
        {
            index = index > 0 ? index - 1 : 0;

            List<string> wheres = new List<string>();

            wheres.Add($"deviceCategory:{(int)DeviceCategory.GPS}");

            if (deviceType.HasValue)
                wheres.Add($"deviceType:{(int)deviceType}");

            if (lifeStatus.HasValue)
                wheres.Add($"liftStatus:{(int)lifeStatus.Value}");

            if (!string.IsNullOrWhiteSpace(model))
                wheres.Add($"Model:/{model}/");

            if (!string.IsNullOrWhiteSpace(accountCode))
                wheres.Add($"AccountCode:/{accountCode}/");

            if (!string.IsNullOrWhiteSpace(imei))
                wheres.Add($"IMEI:/{imei}/");
            if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateDateTime:{$gte:ISODate('" + start.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "'),$lte:ISODate('" + end.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "')}");
            }
            else if (start.HasValue && !end.HasValue)
            { 
                wheres.Add("CreateDateTime:{$gte:ISODate('" + start.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "')}");
            }
            if (end.HasValue && !start.HasValue)
            {
                wheres.Add("CreateDateTime:{$lte:ISODate('" + end.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "')}");
            }

            string str = "{" + string.Join(" , ", wheres) + "}";

            return mongoDBCommand.SelectDocumentsAsync(str, s => s.CreateDateTime, desc, index * size, size).GetAwaiter().GetResult();

        }
        #endregion

        #region 个人用户审查设备是否登记在产品库
        public void PersonDeviceInProductCheck(string imei)
        {
            if (!IsExist(imei))
                throw new ArgumentException($"IMEI[{imei}]设备不在产品库,请检查输入是否正确!"); 
        }
        #endregion
    }
}